package com.stark.commons.spring.web.boot.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.stark.commons.spring.web.boot.properties.EurekaProperties;
import com.stark.commons.spring.web.support.eureka.CanceledEventHandler;
import com.stark.commons.spring.web.support.eureka.CanceledEventListener;
import com.stark.commons.spring.web.support.eureka.DefaultCanceledEventHandler;
import com.stark.commons.spring.web.support.eureka.DefaultRegisteredEventHandler;
import com.stark.commons.spring.web.support.eureka.DefaultRenewedEventHandler;
import com.stark.commons.spring.web.support.eureka.RegisteredEventHandler;
import com.stark.commons.spring.web.support.eureka.RegisteredEventListener;
import com.stark.commons.spring.web.support.eureka.RenewedEventHandler;
import com.stark.commons.spring.web.support.eureka.RenewedEventListener;

/**
 * eureka 自动配置。
 * @author Ben
 * @since 1.0.0
 * @version 1.0.0
 */
@Configuration
@ConditionalOnClass(name = "org.springframework.cloud.netflix.eureka.server.EurekaServerAutoConfiguration")
@EnableConfigurationProperties(EurekaProperties.class)
public class EurekaAutoConfig {
	
	@Autowired(required = false)
	private RegisteredEventHandler registeredEventHandler;
	
	@Autowired(required = false)
	private RenewedEventHandler renewedEventHandler;
	
	@Autowired(required = false)
	private CanceledEventHandler canceledEventHandler;
	
	@Bean
	@ConditionalOnProperty(prefix = "eureka.server", name = "enable-registered-event-listener", havingValue = "true", matchIfMissing = true)
    public RegisteredEventListener registeredEventListener() {
		return new RegisteredEventListener(registeredEventHandler != null ? registeredEventHandler : new DefaultRegisteredEventHandler());
    }
	
	@Bean
	@ConditionalOnProperty(prefix = "eureka.server", name = "enable-renewed-event-listener", havingValue = "true", matchIfMissing = true)
    public RenewedEventListener renewedEventListener() {
		return new RenewedEventListener(renewedEventHandler != null ? renewedEventHandler : new DefaultRenewedEventHandler());
    }
	
	@Bean
	@ConditionalOnProperty(prefix = "eureka.server", name = "enable-canceled-event-listener", havingValue = "true", matchIfMissing = true)
    public CanceledEventListener canceledEventListener() {
		return new CanceledEventListener(canceledEventHandler != null ? canceledEventHandler : new DefaultCanceledEventHandler());
    }

}
